﻿using System;
using System.Collections.Generic;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using OD = DocumentFormat.OpenXml.Drawing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using System.Xml.Linq;

namespace K9Tools.WordTools;

public static class WordImageCombiner
{
    public static int CreateImageDocument(string outputPath,
         string imagePath,
         float scale = 0.95F,
         int imagesPerRow = 3,
         int rowsPerPage = 2)
    {
      //  Logger.Info("图片搜索目录", imagePath);
        var imageList = GetImagesFromDirectory(imagePath);
        if (imageList.Count < 1)
        {
           // Logger.Error("图片搜索目录", "没有找到任何图片文件，请检查路径是否正确。");
            return -1;
        }
       // Logger.Info("图片搜索目录", $"搜索到 {imageList.Count} 个图片文件");

        // 创建 Word 文档
        using var doc = WordprocessingDocument.Create(outputPath, WordprocessingDocumentType.Document);
        // 添加主文档部分
        MainDocumentPart mainPart = doc.AddMainDocumentPart();
        mainPart.Document = new Document(new Body());

        // 设置页面属性（A4，纵向）
        mainPart.Document.Body!.AppendChild(CreatePageSettings());

        // 计算图片尺寸和布局
        var imagesPerPage = imagesPerRow * rowsPerPage;

        // A4 可用尺寸（减去边距，单位：EMU，1英寸 = 914400 EMU）
        var usableWidthEmu = (long)(8.27 * 914400) - (2 * 914400); // 8.27英寸宽度，减去左右边距（各1英寸）
        var usableHeightEmu = (long)(11.69 * 914400) - (2 * 914400); // 11.69英寸高度，减去上下边距
        var imageWidthEmu = (int)(usableWidthEmu / imagesPerRow * scale);
        var imageHeightEmu = (int)(usableHeightEmu / rowsPerPage * scale);

        // 将图片添加到段落
        var paragraph = CreateNewParagraph();

        // 遍历所有图片
        for (var i = 0; i < imageList.Count; i++)
        {
            // 插入图片
            var imageRun = CreateImageElement(mainPart, imageList[i], imageWidthEmu, imageHeightEmu);
            paragraph.AppendChild(imageRun);

            if ((i + 1) % imagesPerRow == 0)
            {
                mainPart.Document.Body.AppendChild(paragraph);
                // 添加分页符（除第一页外）
                if ((i + 1) % imagesPerPage == 0)
                {
                    mainPart.Document.Body.AppendChild(CreatePageBreak());
                }
                paragraph = CreateNewParagraph(); // 创建新的段落
            }
        }

        if (paragraph.ChildElements.Count > 0)
        {
            mainPart.Document.Body.AppendChild(paragraph); // 添加最后一个段落
        }
        // 保存文档
        mainPart.Document.Save();
        //Logger.Info("文档保存成功", outputPath);
        return 0;
    }

    static List<string> GetImagesFromDirectory(string path)
    {
        return Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly)
             .Where(file => file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                            file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                            file.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))
             .OrderBy(a=> int.Parse(Path.GetFileNameWithoutExtension(a)))
             .ToList();
    }

    private static Paragraph CreateNewParagraph()
    {
        return new Paragraph
        {
            ParagraphProperties = new ParagraphProperties(
                new Indentation() { Left = "0", LeftChars = 0, FirstLine = "0", FirstLineChars = 0 }, // 首行不缩进
                new Justification() { Val = JustificationValues.Distribute } // 两端对齐
            )
        };
    }

    // 设置页面属性（A4，纵向）
    private static SectionProperties CreatePageSettings()
    {
        var sectionProps = new SectionProperties(
            new PageSize()
            {
                Width = (UInt32Value)11906U, // A4 宽度（21cm → 11906 单位）
                Height = (UInt32Value)16838U, // A4 高度（29.7cm → 16838 单位）
                Orient = PageOrientationValues.Portrait // 纵向
            },
            new PageMargin()
            {
                Top = 1440,    // 1英寸（1440 单位）
                Right = 1440,  // 1英寸
                Bottom = 1440, // 1英寸
                Left = 1440,   // 1英寸
                Header = 720,  // 0.5英寸
                Footer = 720   // 0.5英寸
            }
        );

        return sectionProps;
    }

    // 添加分页符
    private static OD.Paragraph CreatePageBreak()
    {
        var paragraph = new OD.Paragraph(
            new Run(
                new Break() { Type = BreakValues.Page }
            )
        );
        return paragraph;
    }

    // 插入图片到文档
    private static Run CreateImageElement(MainDocumentPart mainPart,
        string imagePath,
        long widthEmu,
        long heightEmu)
    {
        if (!File.Exists(imagePath))
        {
            throw new FileNotFoundException($"图片文件不存在: {imagePath}");
        }

        var ext = Path.GetExtension(imagePath).ToLowerInvariant();

        var partType = ext switch
        {
            ".jpg" or ".jpeg" => ImagePartType.Jpeg,
            ".png" => ImagePartType.Png,
            _ => throw new NotSupportedException($"不支持的图片格式: {ext}")
        };

        // 添加图片部分
        var imagePart = mainPart.AddImagePart(partType);
        using (var stream = new FileStream(imagePath, FileMode.Open))
        {
            imagePart.FeedData(stream);
        }

        // 生成图片的唯一 ID
        var imageId = mainPart.GetIdOfPart(imagePart);

        // 创建图片元素
        var element = new Drawing(
            new DW.Inline(
                new DW.Extent() { Cx = widthEmu, Cy = heightEmu },
                new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                new DW.DocProperties() { Id = 1U, Name = "Picture" },
                new DW.NonVisualGraphicFrameDrawingProperties(
                    new OD.GraphicFrameLocks() { NoChangeAspect = true }
                ),
                new OD.Graphic(
                    new OD.GraphicData(
                        new PIC.Picture(
                            new PIC.NonVisualPictureProperties(
                                new PIC.NonVisualDrawingProperties() { Id = 0U, Name = "Image" },
                                new PIC.NonVisualPictureDrawingProperties()
                            ),
                            new PIC.BlipFill(
                                new OD.Blip(
                                    new OD.BlipExtensionList(
                                        new OD.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }
                                    )
                                )
                                {
                                    Embed = imageId,
                                    CompressionState = OD.BlipCompressionValues.Print
                                },
                                new OD.Stretch(new OD.FillRectangle())
                            ),
                            new PIC.ShapeProperties(
                                new OD.Transform2D(
                                    new OD.Offset() { X = 0L, Y = 0L },
                                    new OD.Extents() { Cx = widthEmu }
                                ),
                                new OD.PresetGeometry(
                                    new OD.AdjustValueList()
                                )
                                {
                                    Preset = OD.ShapeTypeValues.Rectangle
                                }
                            )
                        )
                    )
                    {
                        Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
                    }
                )
            )
            {
                DistanceFromTop = 0U,
                DistanceFromBottom = 0U,
                DistanceFromLeft = 0U,
                DistanceFromRight = 0U
            }
        );

        // 将图片添加到段落
        return new Run(element);

    }
}